//
//  ZCPaperManager.m
//  ListenAndRead
//
//  Created by TJXF-JY-ZHANGCHENG on 2017/9/25.
//  Copyright © 2017年 www.jsxfedu.com. All rights reserved.
//

#import "ZCPaperManager.h"
#import "ZCFileManager.h"


@interface ZCPaperManager(){
    NSInteger _indexOfSection;
    NSInteger _indexOfQuestion;//-1:题目说明页尚未显示
    BOOL _haveShowSectionHeader;
//    BOOL _haveShowPaperInfo;
}

@property(nonatomic,weak)NSDictionary *paperInfo;
@property(nonatomic,weak)NSArray *sectionArray;

@property(nonatomic,assign)CGFloat answerTotalScore;

@end

@implementation ZCPaperManager

-(NSNumber *)getAnswerTotalScore{
    if (self.answerTotalScore==-1.0f) {
        [self updateCurrentSectionEvaluate];
        CGFloat paperScore = 0.0f;
        NSArray *sectionQuestionArray = self.answerDic[@"paperSections"];
        for (NSDictionary *sectionDic in sectionQuestionArray) {
            NSNumber *sectionScore = sectionDic[@"sectionScore"];
            paperScore += sectionScore.floatValue;
        }
        return [NSNumber numberWithFloat:paperScore];
    }else{
        return [NSNumber numberWithFloat:self.answerTotalScore];
    }
}

+(ZCPaperManager *)sharedInstance{
    static ZCPaperManager *zcPaperManager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        zcPaperManager = [[ZCPaperManager alloc]init];
    });
    return zcPaperManager;
}

-(NSString *)currentPaperType{
    NSString *answerFileMainNameString = @"paper";
    if (self.sectionArray.count==1) {
        NSDictionary *sectionDic = self.sectionArray.lastObject;
        NSDictionary *sectionHeaderDic = sectionDic[@"sectionHeader"];
        NSString *sectionType = sectionHeaderDic[@"sectionType"];
        answerFileMainNameString = sectionType;
    }
    return answerFileMainNameString;
}

-(BOOL)currentPaperIsZXXL{
    return ![[self currentPaperType]isEqualToString:@"paper"];
}

-(void)resetManager{
    self.answerTotalScore = -1.0f;
    _indexOfSection = 0;
//    _indexOfSection = 3;
    _indexOfQuestion = -1;
    self.paperInfo = self.paperDic[@"paperInfo"];
    self.sectionArray = self.paperDic[@"sections"];
    
    NSData *answerData = [[NSData alloc]initWithContentsOfURL:[[NSBundle mainBundle]URLForResource:[NSString stringWithFormat:@"answer_%@",[self currentPaperType]] withExtension:@"json"]];
    NSError *error;
    
    self.answerDic = [NSJSONSerialization JSONObjectWithData:answerData options:NSJSONReadingMutableContainers error:&error];
    
    [self forLowPCClient];
    [self forLowPCClient2];
    NSLog(@"report:%@",self.answerDic);
//    _haveShowPaperInfo = !(self.paperInfo!=nil && [self.paperInfo isKindOfClass:[NSDictionary class]]);
}

-(void)forLowPCClient{
    NSString *paperTypeString = [self currentPaperType];
    if ([paperTypeString isEqualToString:@"paper"] || [paperTypeString isEqualToString:@"cfa_pft"]) {
        NSDictionary *originSectionDic;
        NSDictionary *reportSectionDic;
        if ([paperTypeString isEqualToString:@"paper"]) {
            originSectionDic = self.sectionArray[2];
            reportSectionDic = self.answerDic[@"paperSections"][2];
        }
        if ([paperTypeString isEqualToString:@"cfa_pft"]) {
            originSectionDic = self.sectionArray[0];
            reportSectionDic = self.answerDic[@"paperSections"][0];
        }
        NSMutableDictionary *questionReportDic = reportSectionDic[@"sectionQuestions"][0];
        NSDictionary *questionOriginDic = originSectionDic[@"questionsArray"][0];
        NSDictionary *origionReportCardDic = questionOriginDic[@"reportCard"];
        NSDictionary *question = origionReportCardDic[@"questions"][0];
        NSArray *answersArray = question[@"answers"];
        [questionReportDic setObject:answersArray forKey:@"questionAnswer"];
    }
}

-(NSArray *)initailSentenseArrayForOrigionReportCardDic:(NSDictionary *)origionReportCardDic{
    NSMutableString *mOriginString = [[NSMutableString alloc]init];
    NSArray *originalArray = origionReportCardDic[@"original"];
    for (NSString *string in originalArray) {
        [mOriginString appendFormat:@"%@",string];
    }
    if (mOriginString.length>0) {
        NSString *string = [NSString stringWithFormat:@"%@",mOriginString];
        NSLog(@"string:%@",string);
        NSArray *wordArray = [string componentsSeparatedByString:@" "];
        NSMutableArray *wordsArray = [[NSMutableArray alloc]init];
        for (NSInteger i=0; i<wordArray.count; i++) {
            [wordsArray addObject:@{@"name":wordArray[i],@"score":@(0)}];
        }
        NSDictionary *sentenseDic = @{@"content":string,@"word":wordsArray};
        NSArray *sentenseArray = [[NSArray alloc]initWithObjects:sentenseDic, nil];
        return sentenseArray;
    }else{
        return nil;
    }
}

-(void)forLowPCClient2{
    NSString *paperTypeString = [self currentPaperType];
    if ([paperTypeString isEqualToString:@"paper"] || [paperTypeString isEqualToString:@"pra"]) {
        NSDictionary *originSectionDic;
        NSDictionary *reportSectionDic;
        if ([paperTypeString isEqualToString:@"paper"]) {
            originSectionDic = self.sectionArray[3];
            reportSectionDic = self.answerDic[@"paperSections"][3];
        }
        if ([paperTypeString isEqualToString:@"pra"]) {
            originSectionDic = self.sectionArray[0];
            reportSectionDic = self.answerDic[@"paperSections"][0];
        }
        NSMutableDictionary *questionReportDic = reportSectionDic[@"sectionQuestions"][0];
        NSMutableDictionary *questionRepostAnswerDic = questionReportDic[@"questionAnswer"];
        NSDictionary *questionOriginDic = originSectionDic[@"questionsArray"][0];
        NSDictionary *origionReportCardDic = questionOriginDic[@"reportCard"];
        
        NSArray *sentenseArray = [self initailSentenseArrayForOrigionReportCardDic:origionReportCardDic];
        if (sentenseArray!=nil) {
            [questionRepostAnswerDic setObject:sentenseArray forKey:@"html"];
        }
    }
}

-(void)loadPaper:(NSString *)stringId andGoodsId:(NSString *)goodsId{
    [ZCFileManager sharedInstance].currentId = stringId;
    self.uuidPerDo = [ZCTool getUUIDString];
    
    [[[NSFileManager alloc]init]createDirectoryAtPath:[self currentRecordingDir] withIntermediateDirectories:YES attributes:nil error:nil];
    
    NSData *paperData = [[NSData alloc]initWithContentsOfFile:[NSString stringWithFormat:@"%@/paper.json",[[ZCFileManager sharedInstance]directPathForFileOfCurrentId]]];
    NSError *error;
    self.paperDic = [NSJSONSerialization JSONObjectWithData:paperData options:NSJSONReadingMutableContainers error:&error];
    if (error) {
        [SVProgressHUD showErrorWithStatus:@"不是有效的试卷格式"];
    }else{
        NSLog(@"%@",self.paperDic);
        self.goodsId = [NSString stringWithFormat:@"%@",goodsId];
        [self resetManager];
    }
}

-(NSString *)currentRecordingDir{
    return [[[ZCFileManager sharedInstance]directPathForRecordFileOfCurrentId]stringByAppendingPathComponent:self.uuidPerDo];
}

-(NSString *)currentRecordingFilePath{
    return [[self currentRecordingDir]stringByAppendingPathComponent:[self currentRecordingFileName]];
}

-(void)renameCurrentRecordFileDirBy:(NSString *)reportId{
    NSFileManager *fm = [[NSFileManager alloc]init];
    NSError *error = nil;
    [fm moveItemAtPath:[self currentRecordingDir] toPath:[[[ZCFileManager sharedInstance]directPathForRecordFileOfCurrentId]stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",reportId]] error:&error];
    if (error) {
        NSLog(@"%@",[error localizedDescription]);
    }else{
        self.uuidPerDo = [NSString stringWithFormat:@"%@",reportId];
    }
}

-(NSString *)currentRecordingFileName{
    return [NSString stringWithFormat:@"%@_%@.mp3",@(_indexOfSection+1),@(_indexOfQuestion+1)];
}

-(NSString *)currentSectionType{
    NSDictionary *sectionDic = self.sectionArray[_indexOfSection];
    NSDictionary *sectionHeaderDic = sectionDic[@"sectionHeader"];
    NSString *sectionType = sectionHeaderDic[@"sectionType"];
    return sectionType;
}

-(NSInteger)currentQuestionIndex{
    return _indexOfQuestion;
}

-(NSString *)currentSectionName{
    
    NSString *sectionType = [self currentSectionType];
    
    NSString *resultString = @"未知类型";
    
    if ([sectionType isEqualToString:@"cda"]) {
        resultString = @"听后选择";
    }else if ([sectionType isEqualToString:@"ufj"]){
        resultString = @"听后回答";
    }else if ([sectionType isEqualToString:@"cfa_pft"]){
        resultString = @"听后记录&转述";
    }else if ([sectionType isEqualToString:@"pra"]){
        resultString = @"朗读短文";
    }
    
    return resultString;
}

//-(BasePaperViewController *)paperViewControllerOfType:(NSString *)typeString{
//    if ([typeString isEqualToString:@"cfa_pft"]) {
//        return [[UIStoryboard storyboardWithName:@"Paper" bundle:nil]instantiateViewControllerWithIdentifier:[NSString stringWithFormat:@"cfa_pft%@",@(_indexOfQuestion)]];
//    }else
//        return [[UIStoryboard storyboardWithName:@"Paper" bundle:nil]instantiateViewControllerWithIdentifier:typeString];
//}
//
//-(UIViewController *)rootPaperViewControllerBySuperViewController:(UIViewController *)viewController{
//    self.rootViewController = viewController;
//    if (self.sectionArray!=nil && [self.sectionArray isKindOfClass:[NSArray class]] && self.sectionArray.count>0) {
//        NSDictionary *sectionDic = self.sectionArray[_indexOfSection];
//        NSDictionary *sectionHeaderDic = sectionDic[@"sectionHeader"];
//        NSString *sectionType = sectionHeaderDic[@"sectionType"];
//        if ([sectionType isEqualToString:@"pra"]) {
//            _indexOfQuestion=0;
//            BasePaperViewController *vc = [self paperViewControllerOfType:sectionType];
//
//            NSArray *currentSectionQuestionsArray = sectionDic[@"questionsArray"];
//            NSDictionary *questionDic = currentSectionQuestionsArray[_indexOfQuestion];
//
//            vc.questionDic = questionDic;
//            //朗读题 直接显示题
//            return vc;
//
//        }else{
//            //其它 显示header页面
//            PreviewPaperViewController *vc = [[UIStoryboard storyboardWithName:@"Paper" bundle:nil]instantiateViewControllerWithIdentifier:@"preview"];
//            vc.sectionHeaderDic = sectionHeaderDic;
//            return vc;
//
//        }
//    }else{
//        return nil;
//    }
//}

-(void)updateCurrentSectionEvaluate{
    NSString *sectionType = [self currentSectionType];
    NSMutableDictionary *mDic = self.answerDic[@"paperSections"][_indexOfSection];
    NSArray *sectionQuestionArray = mDic[@"sectionQuestions"];
    CGFloat sectionScore = 0.0f;
    for (NSDictionary *questionDic in sectionQuestionArray) {
        NSNumber *questionScore = questionDic[@"questionScore"];
        sectionScore += questionScore.floatValue;
    }
    [mDic setObject:sectionType forKey:@"sectionType"];
    [mDic setObject:[NSString stringWithFormat:@"%.2f",sectionScore] forKey:@"sectionScore"];
    if ([sectionType isEqualToString:@"cda"]) {
        [mDic setObject:@(12) forKey:@"sectionTotalScore"];
        NSString *sectionEvaluate = @" ";
        if (sectionScore >=10.51f && sectionScore <= 12.0f) {
            sectionEvaluate = @"恭喜你达到了满分水平哦！太棒了！";
        }else if (sectionScore >=9.1f && sectionScore <= 10.5f) {
            sectionEvaluate = @"成绩比较优秀；建议多多练习，更上一层楼哦！";
        }else if (sectionScore >=6.01f && sectionScore <= 9.0f) {
            sectionEvaluate = @"成绩还不错，不过，也出现了少量的错误，要继续练习哦！";
        }else if (sectionScore >=4.51f && sectionScore <= 6.0f) {
            sectionEvaluate = @"成绩不是很理想，要多练习哦！";
        }else if (sectionScore >=1.51f && sectionScore <= 4.5f) {
            sectionEvaluate = @"成绩和别的同学差距较大哦，快快进行听后选择专项练习，提升自己的听力水平吧！";
        }else if (sectionScore >=0.0f && sectionScore <= 1.5f) {
            sectionEvaluate = @"基本是零起点的水平，错误太多了，赶快通过练习来及时补救吧！加油！";
        }
        [mDic setObject:sectionEvaluate forKey:@"sectionEvaluate"];
    }else if ([sectionType isEqualToString:@"ufj"]){
        [mDic setObject:@(10) forKey:@"sectionTotalScore"];
        NSString *sectionEvaluate = @" ";
        if (sectionScore >=7.0f && sectionScore < 10.0f) {
            sectionEvaluate = @"您的回答比较清晰，表意清楚，语音、语调准确，词汇、语法均合乎规范！";
        }else if (sectionScore >=3.0f && sectionScore < 7.0f) {
            sectionEvaluate = @"您未能很好地表意，出现了部分错误，要多练习哦！";
        }else if (sectionScore >=0.0f && sectionScore < 3.0f) {
            sectionEvaluate = @"您未能清晰表意，失分严重！多多学习和练习，一定会有进步的！";
        }
        [mDic setObject:sectionEvaluate forKey:@"sectionEvaluate"];
    }else if ([sectionType isEqualToString:@"cfa_pft"]){
        [mDic setObject:@(10) forKey:@"sectionTotalScore"];
        NSDictionary *question1Dic = sectionQuestionArray[0];
        NSNumber *questionScore = question1Dic[@"questionScore"];
        NSInteger sum = questionScore.integerValue;
        NSString *string = @" ";
        if (sum==5) {
            string = @"恭喜你达到了满分水平哦！太棒了！";
        }else if (sum == 4){
            string = @"成绩比较优秀；建议多多练习，更上一层楼哦！";
            
        }else if (sum == 3){
            string = @"成绩不是很理想，要多练习哦！";
            
        }else if (sum == 2){
            string = @"成绩和别的同学差距较大哦，快快进行听后记录专项练习，提升自己的听后记录水平吧！";
            
        }else if (sum <= 1){
            string = @"基本是零起点的水平，错误太多了，赶快通过练习来及时补救吧！加油！";
        }
        
        NSDictionary *question2Dic = sectionQuestionArray[1];
        NSNumber *questionScore2 = question2Dic[@"questionScore"];
        CGFloat f = questionScore2.floatValue;
        NSString *string2 = @" ";
        
        if (f >= 5.0f && f<5.1f) {
            string2 = @"您的口语表达很优秀，达到了满分水平；讲述很连贯，表达清楚。";
        }else if (f >= 2.0f && f<5.0f){
            string2 = @"你的成绩还不错哦；讲述比较连贯，表达比较清楚，但有一些语法错误。";
            
        }else if (f >= 1.0f && f<2.0f){
            string2 = @"要努力了哦，这题的成绩不太好；讲述不够连贯，错误较多，影响了意思的表达。";
            
        }else if (f >= 0.0f && f<1.0f){
            string2 = @"您的表述未达到评分要求！请加强听后转述题的练习。";
            
        }
        NSString *sectionEvaluate = [NSString stringWithFormat:@"%@%@",string,string2];

        [mDic setObject:sectionEvaluate forKey:@"sectionEvaluate"];

    }else if ([sectionType isEqualToString:@"pra"]){
        [mDic setObject:@(8) forKey:@"sectionTotalScore"];
        
        NSDictionary *questionDic = sectionQuestionArray.lastObject;
        NSString *scoreString = questionDic[@"questionScore"];
        CGFloat score = scoreString.floatValue;
        NSDictionary *questionAnswerDic = questionDic[@"questionAnswer"];
        NSString *fluency_scoreString = questionAnswerDic[@"fluency_score"];
        NSInteger fluency_score = fluency_scoreString.integerValue;
        NSString *accuracy_scoreString = questionAnswerDic[@"accuracy_score"];
        NSInteger accuracy_score = accuracy_scoreString.integerValue;
        NSString *integrity_scoreString = questionAnswerDic[@"integrity_score"];
        NSInteger integrity_score = integrity_scoreString.integerValue;
        NSString *allString = @"";
        NSString *accuracyString = @"";
        NSString *fluencyString = @"";
        NSString *integrityString = @"";
        NSString *overString = @"";
        
        if (accuracy_score >=95 && accuracy_score <=101) {
            accuracyString = @"您的发音比较标准，语音语调正确。";
        }else if(accuracy_score >=80 && accuracy_score <=94) {
            accuracyString = @"您的语音语调基本正确，存在少量错误。";
        }else if(accuracy_score >=60 && accuracy_score <=79) {
            accuracyString = @"您的语音语调不太正确，错误较多。";
        }else if(accuracy_score >=1 && accuracy_score <=59) {
            accuracyString = @"您的发音错误很多，已经影响了意思的表达。";
        }else if(accuracy_score >=0 && accuracy_score <=0) {
            accuracyString = @"您的发音有缺陷，已妨碍对方理解，影响了正常交际。";
        }
        if (fluency_score >=95 && fluency_score <=101) {
            fluencyString = @"您的朗读自然流利，语速适中，有节奏感。";
        }else if(fluency_score >=80 && fluency_score <=94) {
            fluencyString = @"您的朗读比较自然流利。";
        }else if(fluency_score >=60 && fluency_score <=79) {
            fluencyString = @"您的朗读不够连贯。";
        }else if(fluency_score >=1 && fluency_score <=59) {
            fluencyString = @"您的朗读有困难，不连贯。";
        }else if(fluency_score >=0 && fluency_score <=0) {
            fluencyString = @"您的朗读频繁出现非正常停顿，无法完成朗读任务。";
        }
        if (integrity_score >=95 && integrity_score <=101) {
            integrityString = @"能完整清晰地朗读短文。";
        }else if(integrity_score >=80 && integrity_score <=94) {
            integrityString = @"完整度方面能读出绝大多数句子。";
        }else if(integrity_score >=60 && integrity_score <=79) {
            integrityString = @"完整度方面能读出大部分的句子和词汇。";
        }else if(integrity_score >=1 && integrity_score <=59) {
            integrityString = @"完整度方面只读出了少部分的句子和词汇。";
        }else if(integrity_score >=0 && integrity_score <=0) {
            integrityString = @"完整度方面能顺利朗读的句子和词汇过少。";
        }
        
        if (score >=8.0f && score <=8.1f) {
            overString = @"要多多练习，保持您一贯的领先优势哦！";
            allString = @"本题您的得分已经达到了满分水平，太棒了。";

        }else if(score >=5.0f && score <8.0f) {
            overString = @"建议您多进行朗读短文的专项练习，进一步提升自己的成绩！";
            allString = @"您的成绩还不错,建议您多练习，更上一层楼。";

        }else if(score >=2.0f && score <5.0f) {
            overString = @"建议您针对自己的薄弱环节，多进行专项练习，快速提升自己的成绩！";
            allString = @"这次的成绩不太好，要努力了哦。";

        }else if(score >=0 && score <2.0f) {
            overString = @"快快开始朗读专项练习吧，千万不要继续落后了哦！";
            allString = @"您的朗读未达到评分要求，请加强朗读短文题的练习哦。";

        }
        NSString *string = [NSString stringWithFormat:@"%@%@%@%@%@",allString,fluencyString,accuracyString,integrityString,overString];
        
        [mDic setObject:string forKey:@"sectionEvaluate"];
    }
}

-(void)updatePaperEvaluate{
    CGFloat paperScore = 0.0f;
    NSMutableString *mString = [[NSMutableString alloc]init];
    NSArray *sectionQuestionArray = self.answerDic[@"paperSections"];
    for (NSDictionary *sectionDic in sectionQuestionArray) {
        NSNumber *sectionScore = sectionDic[@"sectionScore"];
        paperScore += sectionScore.floatValue;
        [mString appendString:sectionDic[@"sectionEvaluate"]];
    }
    self.answerTotalScore = paperScore;
    [self.answerDic setObject:[NSString stringWithFormat:@"%.2f",self.answerTotalScore] forKey:@"paperScore"];
//    [self.answerDic setObject:mString forKey:@"paperEvaluate"];
}

//-(UIViewController *)nextPaperViewController{
//    NSDictionary *currentSectionDic = self.sectionArray[_indexOfSection];
//    NSArray *currentSectionQuestionsArray = currentSectionDic[@"questionsArray"];
//    _indexOfQuestion++;
//    if (_indexOfQuestion >= currentSectionQuestionsArray.count) {
//        [self updateCurrentSectionEvaluate];
//        _indexOfSection++;
//        _indexOfQuestion=-1;
//        if (_indexOfSection < self.sectionArray.count) {
//            currentSectionDic = self.sectionArray[_indexOfSection];
//            currentSectionQuestionsArray = currentSectionDic[@"questionsArray"];
//        }
//    }
//    
//    if (_indexOfSection >= self.sectionArray.count) {
//        [self updatePaperEvaluate];
//        return nil;
//    }
//    NSDictionary *sectionHeaderDic = currentSectionDic[@"sectionHeader"];
//    NSString *sectionType = sectionHeaderDic[@"sectionType"];
//    if (_indexOfQuestion == -1) {
//        
//        if ([sectionType isEqualToString:@"pra"]) {
//            _indexOfQuestion=0;
//            BasePaperViewController *vc = [self paperViewControllerOfType:sectionType];
//            
//            NSDictionary *questionDic = currentSectionQuestionsArray[_indexOfQuestion];
//            
//            vc.questionDic = questionDic;
//            //朗读题 直接显示题
//            return vc;
//            
//        }else{
//            //其它 显示header页面
//            PreviewPaperViewController *vc = [[UIStoryboard storyboardWithName:@"Paper" bundle:nil]instantiateViewControllerWithIdentifier:@"preview"];
//            vc.sectionHeaderDic = sectionHeaderDic;
//            
//            return vc;
//        }
//    }else{
//        //继续显示当前section的下一题
//        BasePaperViewController *vc = [self paperViewControllerOfType:sectionType];
//        
//        NSDictionary *questionDic = currentSectionQuestionsArray[_indexOfQuestion];
//        
//        vc.questionDic = questionDic;
//        return vc;
//    }
//}

-(void)updateCurrentAnswerDic:(NSDictionary *)currentAnswerDic{
    NSMutableDictionary *mDic = [[NSMutableDictionary alloc]initWithDictionary:currentAnswerDic];
    [mDic setObject:[NSString stringWithFormat:@"%@_%@",@(_indexOfSection+1),@(_indexOfQuestion+1)] forKey:@"number"];
    self.answerDic[@"paperSections"][_indexOfSection][@"sectionQuestions"][_indexOfQuestion] = mDic;
    NSLog(@"%@",self.answerDic);
}

//-(UIViewController *)nextPaperViewControllerWithCurrentAnswer:(NSDictionary *)currentAnswerDic{
//    [self updateCurrentAnswerDic:currentAnswerDic];
//    return [self nextPaperViewController];
//}

-(BOOL)isLastQuestion{
    BOOL result = NO;
    if (self.sectionArray.count == (_indexOfSection+1)) {
        NSDictionary *sectionDic = self.sectionArray[_indexOfSection];
        NSArray *currentSectionQuestionsArray = sectionDic[@"questionsArray"];
        if (currentSectionQuestionsArray.count == (_indexOfQuestion + 1)) {
            result = YES;
        }
    }
    return result;
}

-(NSString *)currentSectionTitle{
    NSDictionary *sectionDic = self.sectionArray[_indexOfSection];
    NSDictionary *sectionHeaderDic = sectionDic[@"sectionHeader"];
    return [NSString stringWithFormat:@"%@",sectionHeaderDic[@"sectionTitle"]];
}

@end
